package com.evildog.workspace.common.framework.chain;

import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 按照顺序执行链上所有对象
 */
@AllArgsConstructor
@NoArgsConstructor
public class TryAllSuccessChain {

    private List<Chain> chainList;

    public TryAllSuccessChain addChain(Chain chain) {
        chainList.add(chain);
        return this;
    }

    public TryAllSuccessChain addChain(Chain... chains) {
        chainList.addAll(Arrays.asList(chains));
        return this;
    }


    /**
     * 按照顺序执行链上的对象，直到某个链返回true
     * <p>
     * 如果执行都失败，返回false
     *
     * @return 返回执行返回false的Chain
     */
    public List<Chain> execute() {
        List<Chain> errorChains = new ArrayList<>();
        for (Chain chain : chainList) {
            if (!chain.execute()) {
                errorChains.add(chain);
            }
        }

        return errorChains;
    }
}
